/**
 * 捕获所有异常
 */
import { ArgumentsHost, Catch, ExceptionFilter,HttpException,HttpStatus  } from '@nestjs/common';
import { Logger } from '../../utils/log4js';
import { Request, Response } from 'express';

@Catch()
export class AnyExceptionFilter<T> implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>()
    const request = ctx.getRequest<Request>()
    const status = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;

    const logFormat = ` <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    Request original url: ${request.originalUrl}
    Method: ${request.method}
    IP: ${request.ip}
    Status code: ${status}
    Response: ${exception.toString()} \n  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<    
    `;
    Logger.error(logFormat);
    response.status(status).json({
      statusCode: status,
      msg: `系统错误: ${exception}`,
    });
  }
}
